package com.magicalcoder.pigeon.common.message;

import com.magicalcoder.pigeon.common.protobuf.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * Created by hzhedongyu on 2017/5/24.
 * 对象编码成二进制
 */
public class PigeonEncoder extends MessageToByteEncoder {
    private Class<?> clazz;
    public PigeonEncoder(Class<?> clazz){
        this.clazz = clazz;
    }
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf out) throws Exception {
        if(clazz.isInstance(o)){
            byte[] bytes = ProtostuffUtil.serialize(o);
            out.writeInt(bytes.length);
            out.writeBytes(bytes);
        }

    }
}
